package ssi.actions;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;

import java.sql.Statement;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;


import ssi.tools.Connector;
import ssi.tools.Tool;

public class CheckLoginAction extends Action {
	public ActionForward execute(ActionMapping mapping, ActionForm form,
				HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		request.setCharacterEncoding("UTF-8");
	
		String email=request.getParameter("email");
		PrintWriter out=response.getWriter();
		
		Connection connection = new Connector().getConnection();
		if(!(email==null || email.equals(""))){
		if(Tool.checkEmailFormat(email)){
		try{
    		Statement statement = connection.createStatement();
    		ResultSet result = statement.executeQuery("SELECT * FROM `users` WHERE email=\""+ email + "\"");
    		if(!(email.equals(""))){
    		if (result.next()){
    			out.println("<font color='red'>Ten uzytkownik istnieje!</font>");
    			result.close();
    			connection.close();		
    		} else {
    			out.println("<font color='green'>Login wolny!</font>");
    			result.close();
    			connection.close();
    		}
    		}else{
    			out.println("<font color='red'>Puste pole loginu!</font>");
    		}
    	} catch(Exception e){
    		out.println("O nie...cos nie dziala:<");
    	}finally{
    		
    		connection.close();
    	}
		}else{
			out.println("<font color='red'>Bledny format email!</font>");
		}
		}else{
			out.println("<font color='red'>Puste pole!</font>");
		}
		
		return null;
	}
	

}
